package com.Xsoft.ShoppingList;

import java.util.ArrayList;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.util.Log;

public class ShoppingListBDAdapter {
	private static final String DATABASE_NAME = "productList.db";
	private static final String DATABASE_TABLE = "productItems";
	private static final int DATABASE_VERSION = 1;

	public static final String KEY_ID = "_id";
	public static final String KEY_PRODUCT = "_product";
	public static final String KEY_CREATION_DATE = "creation_date";
	public static final String KEY_IS_BOUGHT = "is_already_bought";
	public static final String KEY_PRODUCT_CATEGORY = "product_category";
	public static final Integer YES = 1;
	public static final Integer NO = 0;
	public static final String KEY_IS_IN_LIST = "in_list";

	private SQLiteDatabase db;
	private final Context context;
	private ShoppingListDBOpenHelper dbHelper;

	public ShoppingListBDAdapter(Context _context) {
		this.context = _context;
		dbHelper = new ShoppingListDBOpenHelper(context, DATABASE_NAME, null,
				DATABASE_VERSION);
	}

	public void close() {
		db.close();
	}

	public void open() throws SQLiteException {
		try {
			db = dbHelper.getWritableDatabase();
		} catch (SQLiteException ex) {
			db = dbHelper.getReadableDatabase();
		}
	}

	// Insert a new task
	public long insertProduct(Product _product) {
		// Create a new row of values to insert.
		ContentValues newProductValues = new ContentValues();
		// Assign values for each row.
		newProductValues.put(KEY_PRODUCT, _product.getName());
		newProductValues.put(KEY_IS_BOUGHT, _product.isBought() ? YES : NO);
		newProductValues.put(KEY_IS_IN_LIST, _product.isInList() ? YES : NO);
		newProductValues.put(KEY_PRODUCT_CATEGORY, _product.getCategory());
		// Insert the row.
		return db.insert(DATABASE_TABLE, null, newProductValues);
	}

	// Remove a product based on its index
	public boolean removeProduct(long _rowIndex) {
		return db.delete(DATABASE_TABLE, KEY_ID + "=" + _rowIndex, null) > 0;
	}

	public boolean removeAllProducts() {
		return db.delete(DATABASE_TABLE, null, null) > 0;
	}


	public boolean removeBoughtProducts() {
		return db.delete(DATABASE_TABLE, KEY_IS_BOUGHT + "=" + YES, null) > 0;
	}
	public boolean removeToListProducts() {
		return db.delete(DATABASE_TABLE, KEY_IS_IN_LIST + "=" + YES, null) > 0;
	}
	public boolean removeProduct(Product _product) {
		return db.delete(DATABASE_TABLE, KEY_PRODUCT + "=" + "'"+_product.getName()+"'", null) > 0;
	}
	// Update a task
	public boolean updateProduct(long rowIndex, Product product) {
		ContentValues newValue = new ContentValues();
		newValue.put(KEY_PRODUCT, product.getName());
		newValue.put(KEY_IS_BOUGHT, product.isBought() ? YES : NO);
		newValue.put(KEY_IS_IN_LIST, product.isInList() ? YES : NO);
		newValue.put(KEY_PRODUCT_CATEGORY, product.getCategory());
		return db.update(DATABASE_TABLE, newValue, KEY_ID + "=" + rowIndex,
				null) > 0;
	}

	public boolean updateProduct(Product product) {
		ContentValues newValue = new ContentValues();
		db.delete(DATABASE_TABLE, KEY_PRODUCT + "=" + "'" + product.getName()
				+ "'", null);
		return insertProduct(product) > 0;
		// return db.update(DATABASE_TABLE, newValue,
		// "="+"'"+product.getName()+"'",
		// null) > 0;
	}

	public int updateProductList(ArrayList<Product> al) {
		int rowIndex = 0;
		ContentValues newValue = new ContentValues();
		// Iterator<Product> it = aa.iterator();
		Product tempProduct;
		// db.delete(DATABASE_TABLE, null, null);
		for (int i = 0; i < al.size(); i++) {
			tempProduct = al.get(i);
			if (!updateProduct(tempProduct)) {
				insertProduct(tempProduct);
			}

			// newValue.put(KEY_PRODUCT, tempProduct.getName());
			// newValue.put(KEY_IS_BOUGHT, tempProduct.isBought() ? YES : NO);
			// newValue.put(KEY_IS_IN_LIST, YES);
			// db.insert(DATABASE_TABLE, null, newValue);
			// db.update(DATABASE_TABLE, newValue, KEY_ID + "=" + rowIndex++,
			// null);
			// db.query(DATABASE_TABLE, new String[] { KEY_ID,
			// KEY_PRODUCT, KEY_IS_BOUGHT}, null, null, null, null, null);
		}
		return rowIndex;
	}

	public Cursor getAllToProductCursor() {
		return db.query(DATABASE_TABLE, new String[] { KEY_ID, KEY_PRODUCT },
				null, null, null, null, null);
	}

	public Cursor setCursorToProductItem(long _rowIndex) throws SQLException {
		Cursor result = db.query(true, DATABASE_TABLE, new String[] { KEY_ID,
				KEY_PRODUCT }, KEY_ID + "=" + _rowIndex, null, null, null,
				null, null);
		if ((result.getCount() == 0) || !result.moveToFirst()) {
			throw new SQLException("No to do items found for row: " + _rowIndex);
		}
		return result;
	}

	public Product getProduct(Cursor cursor) throws SQLException {
		String name = cursor.getString(cursor.getColumnIndex(KEY_PRODUCT));

		boolean bought = (cursor.getInt(cursor.getColumnIndex(KEY_IS_BOUGHT)) > 0) ? true
				: false;

		boolean inList = (cursor.getInt(cursor.getColumnIndex(KEY_IS_IN_LIST)) > 0) ? true
				: false;
		Product product = new Product(name, bought, inList);
		return product;
	}

	public ArrayList<Product> getAllroducts() {
		ArrayList<Product> al = new ArrayList<Product>();
		Cursor cursor = db.query(DATABASE_TABLE, new String[] { KEY_ID,
				KEY_PRODUCT, KEY_IS_BOUGHT, KEY_IS_IN_LIST,
				KEY_PRODUCT_CATEGORY }, null, null, null, null, null);
		cursor.moveToFirst();
		if (cursor.getCount() > 0) {
			do {
				Product product = getProduct(cursor);
				al.add(product);
			} while (cursor.moveToNext());
		}

		return al;
	}

	private static class ShoppingListDBOpenHelper extends SQLiteOpenHelper {

		public ShoppingListDBOpenHelper(Context context, String name,
				CursorFactory factory, int version) {
			super(context, name, factory, version);
		}

		// // SQL Statement to create a new database.
		private static final String DATABASE_CREATE = "create table "
				+ DATABASE_TABLE + " (" + KEY_ID
				+ " integer primary key autoincrement, " + KEY_PRODUCT
				+ " text not null, " + KEY_IS_BOUGHT + " integer, "
				+ KEY_IS_IN_LIST + " integer, " + KEY_PRODUCT_CATEGORY
				+ " text);";

		// private static final String DATABASE_CREATE = "create table "
		// + DATABASE_TABLE + " (" + KEY_ID
		// + " integer primary key autoincrement, " + KEY_PRODUCT
		// + " text not null, " + KEY_IS_BOUGHT + " integer);";

		@Override
		public void onCreate(SQLiteDatabase _db) {
			_db.execSQL(DATABASE_CREATE);
		}

		@Override
		public void onUpgrade(SQLiteDatabase _db, int _oldVersion,
				int _newVersion) {
			Log.w("TaskDBAdapter", "Upgrading from version " + _oldVersion
					+ " to " + _newVersion
					+ ", which will destroy all old data");

			// Drop the old table.
			_db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
			// Create a new one.
			onCreate(_db);
		}
	}
}
